<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>使用HandlerInterceptor和RateLimiter进行限流 | Eetal&#39;s Blog</title>

  <!-- keywords -->
  

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="欢迎查看Eetal的第十九篇博客–使用HandlerInterceptor和RateLimiter进行限流 为什么使用拦截器目前网上有博客使用的是aop，但是因为我项目里使用了shiro进行权限验证shiro的过滤器链优先级是低于spring的过滤器的所以根据约定优于配置，直接使用过滤器就不需要去配置shiro的一些映射和过滤器的优先级同时网上博客基于aop为注解添加令牌桶效率的属性是有bug的，">
<meta property="og:type" content="article">
<meta property="og:title" content="使用HandlerInterceptor和RateLimiter进行限流">
<meta property="og:url" content="http://eetal.gitee.io/blog/2019/05/26/使用HandlerInterceptor和RateLimiter进行限流/index.html">
<meta property="og:site_name" content="Eetal&#39;s Blog">
<meta property="og:description" content="欢迎查看Eetal的第十九篇博客–使用HandlerInterceptor和RateLimiter进行限流 为什么使用拦截器目前网上有博客使用的是aop，但是因为我项目里使用了shiro进行权限验证shiro的过滤器链优先级是低于spring的过滤器的所以根据约定优于配置，直接使用过滤器就不需要去配置shiro的一些映射和过滤器的优先级同时网上博客基于aop为注解添加令牌桶效率的属性是有bug的，">
<meta property="og:locale" content="default">
<meta property="og:updated_time" content="2019-05-26T13:31:30.678Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="使用HandlerInterceptor和RateLimiter进行限流">
<meta name="twitter:description" content="欢迎查看Eetal的第十九篇博客–使用HandlerInterceptor和RateLimiter进行限流 为什么使用拦截器目前网上有博客使用的是aop，但是因为我项目里使用了shiro进行权限验证shiro的过滤器链优先级是低于spring的过滤器的所以根据约定优于配置，直接使用过滤器就不需要去配置shiro的一些映射和过滤器的优先级同时网上博客基于aop为注解添加令牌桶效率的属性是有bug的，">
  
    <link rel="alternative" href="/atom.xml" title="Eetal&#39;s Blog" type="application/atom+xml">
  
  
    <link rel="icon" href="http://www.yangyitao.top/FiveChess/resource/ico/favicon.ico">
  
  <link rel="stylesheet" href="/blog/css/style.css">
  
  

  <script src="//cdn.bootcss.com/require.js/2.3.2/require.min.js"></script>
  <script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>

  
</head>
<body>
  <div id="container">
    <div id="particles-js"></div>
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
	<header id="header" class="inner">
		<a href="/" class="profilepic">
			
			<img lazy-src="/blog/images/head.jpg" class="js-avatar">
			
		</a>

		<hgroup>
		  <h1 class="header-author"><a href="/">Eetal</a></h1>
		</hgroup>

		
		<p class="header-subtitle">java coder</p>
		

		
			<div class="switch-btn">
				<div class="icon">
					<div class="icon-ctn">
						<div class="icon-wrap icon-house" data-idx="0">
							<div class="birdhouse"></div>
							<div class="birdhouse_holes"></div>
						</div>
						<div class="icon-wrap icon-ribbon hide" data-idx="1">
							<div class="ribbon"></div>
						</div>
						
						<div class="icon-wrap icon-link hide" data-idx="2">
							<div class="loopback_l"></div>
							<div class="loopback_r"></div>
						</div>
						
						
					</div>
					
				</div>
				<div class="tips-box hide">
					<div class="tips-arrow"></div>
					<ul class="tips-inner">
						<li>菜单</li>
						<li>标签</li>
						
						<li>友情链接</li>
						
						
					</ul>
				</div>
			</div>
		

		<div class="switch-area">
			<div class="switch-wrap">
				<section class="switch-part switch-part1">
					<nav class="header-menu">
						<ul>
						
							<li><a href="/blog/">Home</a></li>
				        
							<li><a href="/blog/archives">Archives</a></li>
				        
						</ul>
					</nav>
					<nav class="header-nav">
						<div class="social">
							
						</div>
					</nav>
				</section>
				
				
				<section class="switch-part switch-part2">
					<div class="widget tagcloud" id="js-tagcloud">
						
					</div>
				</section>
				
				
				
				<section class="switch-part switch-part3">
					<div id="js-friends">
					
			          <a target="_blank" class="main-nav-link switch-friends-link" href="https://github.com/smackgg/hexo-theme-smackdown">smackdown</a>
			        
			        </div>
				</section>
				

				
			</div>
		</div>
	</header>				
</div>
    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
  	<div class="overlay">
  		<div class="slider-trigger"></div>
  		<h1 class="header-author js-mobile-header hide">Eetal</h1>
  	</div>
	<div class="intrude-less">
		<header id="header" class="inner">
			<div class="profilepic">
				<img lazy-src="/blog/images/head.jpg" class="js-avatar">
			</div>
			<hgroup>
			  <h1 class="header-author">Eetal</h1>
			</hgroup>
			
			<p class="header-subtitle">java coder</p>
			
			<nav class="header-menu">
				<ul>
				
					<li><a href="/blog/">Home</a></li>
		        
					<li><a href="/blog/archives">Archives</a></li>
		        
		        <div class="clearfix"></div>
				</ul>
			</nav>
			<nav class="header-nav">
				<div class="social">
					
				</div>
			</nav>
		</header>				
	</div>
</nav>
      <div class="body-wrap"><article id="post-使用HandlerInterceptor和RateLimiter进行限流" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="/blog/2019/05/26/使用HandlerInterceptor和RateLimiter进行限流/" class="article-date">
  	<time datetime="2019-05-26T12:56:27.192Z" itemprop="datePublished">2019-05-26</time>
</a>
    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      使用HandlerInterceptor和RateLimiter进行限流
      
    </h1>
  

      </header>
      
      <div class="article-info article-info-post">
        
        

        
        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>欢迎查看Eetal的第十九篇博客–使用HandlerInterceptor和RateLimiter进行限流</p>
<h2 id="为什么使用拦截器"><a href="#为什么使用拦截器" class="headerlink" title="为什么使用拦截器"></a>为什么使用拦截器</h2><p>目前网上有博客使用的是aop，但是因为我项目里使用了shiro进行权限验证<br>shiro的过滤器链优先级是低于spring的过滤器的<br>所以根据约定优于配置，直接使用过滤器就不需要去配置shiro的一些映射和过滤器的优先级<br>同时网上博客基于aop为注解添加令牌桶效率的属性是有bug的，因为springMVC多线程是Method级别<br>而在aop的切面里创建rateLimiter或者为拿到的method对象的annotation对象绑定一个rateLimiter都会有线程问题<br>基于以上，把ratelimiter拿到拦截器，如果要定义不同rateLimiter可以改为定义多个拦截器和注解</p>
<h2 id="常见限流算法"><a href="#常见限流算法" class="headerlink" title="常见限流算法"></a>常见限流算法</h2><p>常见的限流方法有信号量计数器（Semaphore）计数当前线程个数<br>漏桶算法—使用一个容器保存进来的任务，按照固定速率流出任务，桶满时新加入的任务直接流出<br>令牌桶算法—使用一个容器存储令牌，按照固定速率生产令牌，令牌桶满时直接丢弃新生成令牌，任务进来以后尝试获取令牌，获取成功的任务开始执行<br>计数器较麻烦，需要维护实时记录线程数，完成时进行维护<br>对比令牌桶和漏桶，漏桶算法无法解决当容量空闲了一段时间以后，大量任务一起进来时，执行的平均效率低下的问题，而令牌桶的令牌生成速率是固定的</p>
<h2 id="rateLimiter介绍"><a href="#rateLimiter介绍" class="headerlink" title="rateLimiter介绍"></a>rateLimiter介绍</h2><p>RateLimiter是guava提供的基于令牌桶算法的实现类<br>create（Double permitsPerSecond）方法根据给定的（令牌:单位时间（1s））比例为令牌生成速率<br>tryAcquire（）方法尝试获取一个令牌，立即返回true/false，不阻塞，重载方法具备设置获取令牌个数、获取最大等待时间等参数<br>acquire（）方法与tryAcquire类似，但是会阻塞，尝试获取一个令牌，没有时则阻塞直到获取成功</p>
<h2 id="注解创建"><a href="#注解创建" class="headerlink" title="注解创建"></a>注解创建</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">@Target(ElementType.METHOD)</span><br><span class="line">@Retention(RetentionPolicy.RUNTIME)</span><br><span class="line">@Documented</span><br><span class="line">public @interface RateLimit &#123;</span><br><span class="line"> </span><br><span class="line">    /**</span><br><span class="line">     * 获取令牌的等待时间  默认0</span><br><span class="line">     * @<span class="built_in">return</span></span><br><span class="line">     */</span><br><span class="line">	int value() default 0;</span><br><span class="line"></span><br><span class="line"> </span><br><span class="line">    /**</span><br><span class="line">     * 超时时间单位</span><br><span class="line">     * @<span class="built_in">return</span></span><br><span class="line">     */</span><br><span class="line">    TimeUnit timeOutUnit() default TimeUnit.MILLISECONDS;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="拦截器"><a href="#拦截器" class="headerlink" title="拦截器"></a>拦截器</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">public class RateLimitInterceptor implements HandlerInterceptor &#123;</span><br><span class="line"> </span><br><span class="line">    private final static Logger logger = LoggerFactory.getLogger(RateLimitInterceptor.class);</span><br><span class="line">    </span><br><span class="line">    //每s产生2000个令牌</span><br><span class="line">    RateLimiter rateLimiter = RateLimiter.create(2000);</span><br><span class="line"> </span><br><span class="line">    @Override</span><br><span class="line">    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,</span><br><span class="line">                             Object handler) throws Exception &#123;</span><br><span class="line">        //如果是SpringMVC请求</span><br><span class="line">        <span class="keyword">if</span>(handler instanceof HandlerMethod)&#123;</span><br><span class="line">            HandlerMethod handlerMethod = (HandlerMethod) handler;</span><br><span class="line">            RateLimit rateLimit = handlerMethod.getMethodAnnotation(RateLimit.class);</span><br><span class="line">            <span class="keyword">if</span>(rateLimit != null) &#123;</span><br><span class="line">            	logger.info(<span class="string">"rateLimit intercept method..."</span>);</span><br><span class="line">            	<span class="keyword">if</span> (!rateLimiter.tryAcquire(rateLimit.value(), rateLimit.timeOutUnit())) &#123;</span><br><span class="line">            		throw new Exception(<span class="string">"系统繁忙，新稍后再试!"</span>);</span><br><span class="line">					//这里抛出异常是因为我项目里对异常进行了全局处理</span><br><span class="line">                 &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="springBoot拦截器配置"><a href="#springBoot拦截器配置" class="headerlink" title="springBoot拦截器配置"></a>springBoot拦截器配置</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">@Configuration</span><br><span class="line">public class WebMVCConfig implements WebMvcConfigurer &#123;</span><br><span class="line">    </span><br><span class="line">    @Override</span><br><span class="line">    public void addInterceptors(InterceptorRegistry registry) &#123;</span><br><span class="line">        registry.addInterceptor(new RateLimitInterceptor()).addPathPatterns(<span class="string">"/**"</span>)</span><br><span class="line">                .excludePathPatterns(<span class="string">"/static/**"</span>, <span class="string">"/"</span>);</span><br><span class="line">				//配置限流拦截器拦截以及不拦截的映射</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="开始使用"><a href="#开始使用" class="headerlink" title="开始使用"></a>开始使用</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">@RateLimit(1000)	//最大等待时间1s</span><br><span class="line">@RequestMapping(<span class="string">"/login"</span>)</span><br><span class="line">public ModelAndView login(User user) &#123;</span><br><span class="line">	ModelAndView mv = new ModelAndView();</span><br><span class="line">	String username=user.getUsername();</span><br><span class="line">	String password=user.getPassword();</span><br><span class="line">	UsernamePasswordToken token = new UsernamePasswordToken(username,password,<span class="literal">false</span>);</span><br><span class="line">	Subject subject = SecurityUtils.getSubject();</span><br><span class="line">	try &#123;</span><br><span class="line">		subject.login(token);</span><br><span class="line">	&#125; catch(IncorrectCredentialsException e)&#123;</span><br><span class="line">		mv.addObject(<span class="string">"msg"</span>, <span class="string">"密码错误"</span>);</span><br><span class="line">		mv.setViewName(<span class="string">"/login.html"</span>);</span><br><span class="line">		<span class="built_in">return</span> mv;</span><br><span class="line">	&#125; catch (AuthenticationException e) &#123;</span><br><span class="line">		mv.addObject(<span class="string">"msg"</span>, <span class="string">"登录失败"</span>);</span><br><span class="line">		mv.setViewName(<span class="string">"/login.html"</span>);</span><br><span class="line">		<span class="built_in">return</span> mv;</span><br><span class="line">	&#125;		</span><br><span class="line">	</span><br><span class="line">	mv.addObject(<span class="string">"userDto"</span>,(UserDto)subject.getSession().getAttribute(<span class="string">"userDto"</span>));</span><br><span class="line">	mv.setViewName(<span class="string">"/index.html"</span>);</span><br><span class="line">	<span class="built_in">return</span> mv;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="请移步"><a href="#请移步" class="headerlink" title="请移步"></a>请移步</h3><p>个人主页: <a href="http://yangyitao.top" target="_blank" rel="noopener">yangyitao.top</a></p>

      
    </div>
    
  </div>
  
    
<nav id="article-nav">
  
    <a href="/blog/2019/06/05/springCloud的LoadBalance源码分析/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">&lt;</strong>
      <div class="article-nav-title">
        
          SpringCloud的LoadBalance源码分析
        
      </div>
    </a>
  
  
    <a href="/blog/2019/04/12/字符串常量池在1.6与1.8以及String、StringBuffer、StringBuilder/" id="article-nav-older" class="article-nav-link-wrap">
      <div class="article-nav-title">字符串常量池在1.6与1.8以及String、StringBuffer、StringBuilder</div>
      <strong class="article-nav-caption">&gt;</strong>
    </a>
  
</nav>

  
</article>


<div class="ds-share share" data-thread-key="使用HandlerInterceptor和RateLimiter进行限流" data-title="使用HandlerInterceptor和RateLimiter进行限流" data-url="http://eetal.gitee.io/blog/blog/2019/05/26/使用HandlerInterceptor和RateLimiter进行限流/"  data-images="/blog/images/head.jpg" data-content="使用HandlerInterceptor和RateLimiter进行限流">
    <div class="ds-share-inline">
      <ul  class="ds-share-icons-16">
      	<li data-toggle="ds-share-icons-more"><a class="ds-more" href="javascript:void(0);">分享到：</a></li>
        <li><a class="ds-weibo" href="javascript:void(0);" data-service="weibo">微博</a></li>
        <li><a class="ds-qzone" href="javascript:void(0);" data-service="qzone">QQ空间</a></li>
        <li><a class="ds-qqt" href="javascript:void(0);" data-service="qqt">腾讯微博</a></li>
        <li><a class="ds-wechat" href="javascript:void(0);" data-service="wechat">微信</a></li>
      </ul>
      <div class="ds-share-icons-more">
      </div>
    </div>
 </div>
 





</div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info">
      <div class="footer-left">
        &copy; 2019 Eetal
      </div>
        <div class="footer-right">
          <a href="http://hexo.io/" target="_blank">Hexo</a>  Theme <a href="https://github.com/smackgg/hexo-theme-smackdown" target="_blank">Smackdown</a>
        </div>
    </div>
  </div>
</footer>
    </div>
    
  <link rel="stylesheet" href="/blog/fancybox/jquery.fancybox.css">


<script>
	var yiliaConfig = {
		fancybox: true,
		mathjax: true,
		animate: true,
		isHome: false,
		isPost: true,
		isArchive: false,
		isTag: false,
		isCategory: false,
		open_in_new: false
	}
</script>
<script src="/blog/js/main.js"></script>



<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';                 
    }       
});
</script>

<script src="//cdn.bootcss.com/mathjax/2.7.0/MathJax.js"></script>


  </div>
</body>
</html>